package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import cn.tedu.charging.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;
@Configuration
@Slf4j
public class MqttClientConfiguration {
    //charging.emqx.address
    @Value("${charging.emqx.address}")
    private String address;
    @Value("${charging.emqx.username}")
    private String username;
    @Value("${charging.emqx.password}")
    private String password;
    @Autowired
    private MqttContext mqttContext;
    @Bean
    public MqttClient mqttClientInit(){
        MqttClient mqttClient = null;
        try {
            String uuid= UUID.randomUUID().toString();
            mqttClient=new MqttClient(address,uuid,new MemoryPersistence());
            MqttConnectOptions options=new MqttConnectOptions();
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            MqttCallback callback=new MqttConsumer(mqttClient,mqttContext);
            mqttClient.setCallback(callback);
            mqttClient.connect(options);
        }catch (Exception e){
            log.error("mqtt客户端初始化失败",e);
        }
        return mqttClient;
    }













}
